package com.orange.shirotest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;

import java.util.Arrays;

public class ShiroRun {
    public static void main(String[] args) {
        //1.初始化获取SecurityManager
        //2.获取Subject对象
        //3.创建token对象，web应用用户名和密码从页面传递
        //4.完成登录
        //5.判断角色
        //6.判断权限

        //1.初始化获取SecurityManager
        IniSecurityManagerFactory factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        SecurityManager securityManager = factory.getInstance();
        SecurityUtils.setSecurityManager(securityManager);

        //2.获取Subject对象
        Subject subject = SecurityUtils.getSubject();

        //3.创建token对象，web应用用户名和密码从页面传递
        AuthenticationToken token = new UsernamePasswordToken("zhangsan", "z3");

        //4.完成登录
        try {
            subject.login(token);
            System.out.println("登录成功 success");

            //5.判断角色
            boolean hasRole = subject.hasRole("role1");
            System.out.println("是否拥有role1角色 = " + hasRole);
            System.out.println(
                    Arrays.toString(subject.hasRoles(Arrays.asList("role1","role2")))
            );

            //6.判断权限
            boolean permitted = subject.isPermitted("user:insert");
            System.out.println("是否拥有user:insert权限 = " + permitted);
            //也可以用checkPermission方法，但没有返回值，没权限抛出AuthenticationException
            //subject.checkPermission("user:select11");
            subject.checkPermission("user:select");

        } catch (UnknownAccountException e) {
            e.printStackTrace();
            System.out.println("用户不存在");
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            System.out.println("密码错误");
        } catch (AuthenticationException e) {
            e.printStackTrace();
        }finally {
            // 7:判断是否登录成功
            System.out.println("是否登录成功："+subject.isAuthenticated());
            subject.logout();
            System.out.println("是否登录成功："+subject.isAuthenticated());
        }
    }
}